<?php

namespace app\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Lang;

class JwtService
{
    /**
     * 生成JWT令牌
     *
     * @param array $payload 载荷数据
     * @param int $expire 过期时间（秒）
     * @return string
     */
    public static function createToken($payload, $expire = 86400)
    {
        $key = config('app.jwt_key');
        $time = time();
        
        $payload['iat'] = $time; // 签发时间
        $payload['exp'] = $time + $expire; // 过期时间
        
        return JWT::encode($payload, $key, 'HS256');
    }
    
    /**
     * 验证JWT令牌
     *
     * @param string $token JWT令牌
     * @return array|bool 成功返回载荷数据，失败返回false
     */
    public static function verifyToken($token)
    {
        try {
            $key = config('app.jwt_key');
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
            return (array)$decoded;
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * 从请求头中获取JWT令牌
     *
     * @return string|null
     */
    public static function getTokenFromHeader()
    {
        $header = request()->header('Authorization');
        if (empty($header)) {
            return null;
        }
        
        $parts = explode(' ', $header);
        if (count($parts) !== 2 || strtolower($parts[0]) !== 'bearer') {
            return null;
        }
        
        return $parts[1];
    }
}
